from django.db import models
from ordered_model.models import OrderedModel
from django.db.models import JSONField  # 使用 Django 核心的 JSONField
from colorfield.fields import ColorField

class Article(models.Model):
    # 文章类型选项
    TYPE_CHOICES = [
        ('weburl', '网页链接'),
        ('video', '视频'),
    ]
    
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=255)  # 文章标题
    type = models.CharField(max_length=10, choices=TYPE_CHOICES)  # 文章类型
    url = models.URLField(blank=True, null=True)  # URL字段，非强制填写
    column = models.CharField(max_length=255)  # 栏目字段，必填
    date = models.DateField(blank=True, null=True)  # 日期字段，可选
    image_url = models.CharField(max_length=255, blank=True, null=True)  # 图片URL字段，可选
    
    class Meta:
        verbose_name = "文章"
        verbose_name_plural = "文章"
    
    def __str__(self):
        return self.title  # 返回文章标题作为对象的字符串表示

# 在Article模型定义之后添加

class ArticleGroup(models.Model):
    """文章内容组 - 最外层结构"""
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=255, verbose_name="标题")
    description = models.TextField(blank=True, null=True, verbose_name="描述")
    articles = models.ManyToManyField(Article, related_name='article_groups', verbose_name="文章", blank=True)
    
    class Meta:
        verbose_name = "文章-内容组"
        verbose_name_plural = "文章-内容组"
        ordering = ['title']
    
    def __str__(self):
        return self.title

    def articles_count(self):
        return self.articles.count()
    articles_count.short_description = '文章数量'
    
# 删除以下ArticleGroupArticle模型定义
# class ArticleGroupArticle(models.Model):
#     """文章内容组与文章的关联"""
#     article_group = models.ForeignKey(ArticleGroup, on_delete=models.CASCADE)
#     article = models.ForeignKey(Article, on_delete=models.CASCADE)
#     date_added = models.DateTimeField(auto_now_add=True, verbose_name="添加时间")
#     
#     class Meta:
#         unique_together = ('article_group', 'article')
#         ordering = ['-date_added']  # 默认按添加时间倒序排列
#     
#     def __str__(self):
#         return f"{self.article_group.title} - {self.article.title}"

    
# 从这里开始是其他模型的定义
class Mission(models.Model):
    id = models.AutoField(primary_key=True)
    institution = models.CharField(max_length=255)
    mission_name = models.CharField(max_length=255)
    launch_time = models.CharField(max_length=255)
    image_url = models.CharField(max_length=255, blank=True, null=True)
    header_image = models.CharField(max_length=255, blank=True, null=True)
    status = models.CharField(max_length=50)
    launch_time_utc = models.DateTimeField()
    recommend = models.BooleanField(default=False)
    is_displayable = models.BooleanField(default=True, verbose_name="是否展示")
    is_countable = models.BooleanField(default=True, verbose_name="是否统计")
    class Meta:
        verbose_name = "任务-发射"
        verbose_name_plural = "任务-发射"
        ordering = ['-launch_time_utc']  # 按UTC时间倒序排列

    def __str__(self):
        return self.mission_name
    
    # def save(self, *args, **kwargs):
    #     # 调用父类的 save 方法保存当前实例
    #     super().save(*args, **kwargs)

    #     # 检查是否存在对应的 MissionDetail 实例
    #     if not hasattr(self, 'detail'):  # 如果没有 detail 属性，说明还没有关联的 MissionDetail
    #         MissionDetail.objects.create(mission=self)  # 自动创建 MissionDetail 实例

########################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
#########任务详情#########
class MissionDetail(models.Model):
    mission = models.OneToOneField(
        Mission,
        on_delete=models.CASCADE,
        primary_key=True,
        related_name='任务名称'
    )

    new_related_groups = models.ManyToManyField(
        'TaskRelation',
        through='MissionDetailTaskRelation',
        verbose_name='关联任务组'
    )

    crew_members = models.ManyToManyField(
        'Astronaut',
        through='MissionCrewMember',
        related_name='missions',
        verbose_name='乘组成员'
    )

    # 新增机构字段
    institutions = models.ManyToManyField(
        'Institution',
        through='MissionInstitutionMember',
        related_name='missions',
        verbose_name='参与机构'
    )

    launch_site = models.ForeignKey(
        'LaunchSite',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name="发射场"
    )
    
    # 新增文章字段
    # 直接绑定的文章内容组（可选）
    article_group = models.ForeignKey(
        'ArticleGroup',
        on_delete=models.SET_NULL,
        null=True,
        blank=True,
        verbose_name="绑定的文章内容组"
    )
    
    # 多对多关联的文章
    articles = models.ManyToManyField(
        'Article',
        related_name='mission_details',
        verbose_name="关联的文章",
        blank=True
    )

    class Meta:
        verbose_name = "任务-详情关联"
        verbose_name_plural = "任务-详情关联"
    
    def __str__(self):
        return f"详情: {self.mission.mission_name}"

class MissionCrewMember(models.Model):
    mission_detail = models.ForeignKey(MissionDetail, on_delete=models.CASCADE)
    astronaut = models.ForeignKey('Astronaut', on_delete=models.CASCADE)
    role = models.CharField(max_length=100, verbose_name="任务身份")  # 比如：指令长、飞行工程师等
    order = models.PositiveIntegerField(default=0, db_index=True)  # 用于排序显示

    class Meta:
        ordering = ['order']
        verbose_name = "任务乘组成员"
        verbose_name_plural = "任务乘组成员"

    def __str__(self):
        return f"{self.astronaut.chinese_name} - {self.role}"
    
    
class TaskRelation(models.Model):
    relation_id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255)
    description = models.TextField()
    image_url = models.CharField(max_length=255, verbose_name="图片URL", blank=True, null=True)
    related_missions = models.ManyToManyField(
        Mission, 
        related_name='missions_relation'
    )  # 关联任务
    class Meta:
        verbose_name = "关联任务组"
        verbose_name_plural = "关联任务组"
    def __str__(self):
        return self.name

class MissionDetailTaskRelation(models.Model):
    mission_detail = models.ForeignKey(MissionDetail, on_delete=models.CASCADE)
    task_relation = models.ForeignKey('TaskRelation', on_delete=models.CASCADE)

    order = models.PositiveIntegerField(default=0, editable=False, db_index=True)  # 排序字段
    
    class Meta(OrderedModel.Meta):
        ordering = ['order']

    def __str__(self):
        return f"{self.mission_detail} - {self.task_relation} (Order: {self.order})"
    
########################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################
class MissionStatus(models.Model):
    COLOR_CHOICES = [
        ('#396DF2', '蓝色'),
        ('#FF0C0C', '红色'),
        ('#FF9600', '黄色'),
    ]
    
    mission = models.OneToOneField(
        'Mission',
        on_delete=models.CASCADE,
        related_name='status_data'
    )
    status = models.CharField(max_length=255, verbose_name="状态")
    description = models.TextField(verbose_name="描述")
    color = ColorField(
        default='#396DF2',
        verbose_name="颜色",
        help_text="选择预设颜色或自定义颜色",
        samples=COLOR_CHOICES
    )

    class Meta:
        verbose_name = "任务-状态卡片"
        verbose_name_plural = "任务-状态卡片"

    def __str__(self):
        return f"{self.mission.mission_name} 的状态: {self.status}"


class MissionBasicInfo(models.Model):
    COUNTRY_CHOICES = [
        ('america', '美国'),
        ('china', '中国'),
        ('russia', '俄罗斯'),
        ('europe', '欧洲'),
        ('japan', '日本'),
        ('india', '印度'),
        ('german', '德国'),
    ]
    
    mission = models.OneToOneField(
        'Mission',
        on_delete=models.CASCADE,
        related_name='basic_info'
    )
    country = models.CharField(max_length=100, choices=COUNTRY_CHOICES, verbose_name="国家")
    institution = models.CharField(max_length=255, verbose_name="机构")
    rocket_name = models.CharField(max_length=255, verbose_name="火箭名称")
    payload_info = models.CharField(max_length=255, verbose_name="载荷信息", blank=True, null=True)
    launch_site = models.CharField(max_length=255, verbose_name="发射场", blank=True, null=True)
    mini_tags = JSONField(default=list, verbose_name="标签")
    badge_url = models.CharField(max_length=255, verbose_name="徽章标志URL", blank=True, null=True)
    badge_text = models.CharField(max_length=255, verbose_name="标志说明", blank=True, default="")

    class Meta:
        verbose_name = "任务-基本信息"
        verbose_name_plural = "任务-基本信息"

    def __str__(self):
        return f"{self.mission.mission_name} 的基本信息"

    @staticmethod
    def get_default_mini_tags():
        return [
            {"title": "发射工位", "content": ""},
            {"title": "目标轨道", "content": ""},
            {"title": "任务性质", "content": ""},
            {"title": "发射窗口", "content": ""},
        ]

    def save(self, *args, **kwargs):
        if not self.mini_tags:
            self.mini_tags = self.get_default_mini_tags()
        super().save(*args, **kwargs)

class MissionContent(models.Model):
    mission = models.OneToOneField(
        'Mission',
        on_delete=models.CASCADE,
        related_name='content_data'
    )
    content = JSONField(default=list, verbose_name="内容")
    class Meta:
        verbose_name = "任务-介绍"
        verbose_name_plural = "任务-介绍"
    @staticmethod
    def get_default_content():
        return [
            {"type": "h2", "content": "任务目标"},
            {"type": "p", "content": "请在此填写任务目标描述..."},
            {"type": "img", "url": "/images/default.jpg"},
        ]

    def save(self, *args, **kwargs):
        if not self.content:
            self.content = self.get_default_content()
        super().save(*args, **kwargs)

class Astronaut(models.Model):
    STATUS_CHOICES = [('active', '在役'), ('retired', '已退役'), ('deceased', '已去世')]
    GENDER_CHOICES = [('MALE', '男'), ('FEMALE', '女')]
    COUNTRY_CHOICES = [
        ('america', '美国'),
        ('china', '中国'),
        ('russia', '俄罗斯'),
        ('europe', '欧洲'),
        ('japan', '日本'),
        ('india', '印度'),
        ('german', '德国'),
    ]
    
    id = models.AutoField(primary_key=True)
    chinese_name = models.CharField(max_length=255, verbose_name="中文名")
    english_name = models.CharField(max_length=255, verbose_name="英文名")
    gender = models.CharField(max_length=6, choices=GENDER_CHOICES, default='MALE', verbose_name="性别")
    country = models.CharField(max_length=100, choices=COUNTRY_CHOICES, default='china', verbose_name="国家")
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name="状态")
    image_url = models.CharField(max_length=255, verbose_name="照片URL", blank=True, null=True)
    content = models.JSONField(default=list, verbose_name="介绍内容", blank=True)  # 直接在模型中添加JSON字段
    
    class Meta:
        verbose_name = "内容-宇航员"
        verbose_name_plural = "内容-宇航员"
        ordering = ['chinese_name']  # 按中文名排序
    
    def __str__(self):
        return self.chinese_name
    
    @staticmethod
    def get_default_content():
        return [
            {"type": "h2", "content": "个人简介"},
            {"type": "p", "content": "请在此填写宇航员个人简介..."},
            {"type": "img", "url": "/images/astronauts/default.jpg", "description": ""},
            {"type": "h2", "content": "航天经历"},
            {"type": "p", "content": "请在此填写宇航员的航天经历..."},
            {"type": "h2", "content": "主要成就"},
            {"type": "p", "content": "请在此填写宇航员的主要成就..."},
        ]
    
    def save(self, *args, **kwargs):
        if not self.content:
            self.content = self.get_default_content()
        super().save(*args, **kwargs)



def get_launch_site_default_basic_info():
    return [
        {"title": "英文名", "content": ""},
        {"title": "别称/简称", "content": ""},
        {"title": "所属国家", "content": ""},            
        {"title": "所属机构", "content": ""},
        {"title": "纬度位置", "content": ""},
    ]

def get_launch_site_default_content():
    return [
        {"type": "h1", "content": "发射场介绍"},
        {"type": "p", "content": "请在此填写发射场介绍..."},
        {"type": "img", "url": "/images/launchsites/default.jpg", "description": ""},
        {"type": "h1", "content": "发射场图片"},
        {"type": "img", "url": "/images/launchsites/area_default.jpg", "description": ""},
    ]

class LaunchSite(models.Model):
    LATITUDE_CHOICES = [
        ('low', '低纬度'),
        ('middle', '中纬度'),
        ('high', '高纬度'),
    ]
    
    LOCATION_CHOICES = [
        ('coastal', '沿海'),
        ('inland', '内陆'),
    ]
    
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, verbose_name="发射场名称")
    location = models.CharField(max_length=255, verbose_name="位置")
    active_pads = models.PositiveIntegerField(verbose_name="活跃工位数")
    latitude_type = models.CharField(max_length=10, choices=LATITUDE_CHOICES, verbose_name="纬度位置")
    location_type = models.CharField(max_length=10, choices=LOCATION_CHOICES, verbose_name="地理位置")
    image_url = models.CharField(max_length=255, verbose_name="图片URL")
    basic_info = models.JSONField(default=get_launch_site_default_basic_info, verbose_name="基本信息表格")
    content = models.JSONField(default=get_launch_site_default_content, verbose_name="正文内容")
    order = models.PositiveIntegerField(default=0, verbose_name="排序", db_index=True)  # 新增这行
    
    class Meta:
        verbose_name = "发射场"
        verbose_name_plural = "发射场"
        ordering = ['order']  # 按order字段排序
    
    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)


def get_encyclopedia_default_content():
    return [
        {"type": "h1", "content": "概述"},
        {"type": "p", "content": "请在此填写百科词条的概述内容..."},
        {"type": "img", "url": "/images/encyclopedia/default.jpg", "description": ""},
        {"type": "h2", "content": "详细介绍"},
        {"type": "p", "content": "请在此填写详细介绍内容..."},
    ]

class Encyclopedia(models.Model):
    id = models.AutoField(primary_key=True)
    type = models.CharField(max_length=100, verbose_name="类型")
    name = models.CharField(max_length=255, verbose_name="名称")
    alias = models.CharField(max_length=255, verbose_name="别名", blank=True, null=True)
    url = models.CharField(max_length=500, verbose_name="相关链接", blank=True, null=True)
    tags = models.CharField(max_length=500, verbose_name="标签", blank=True, null=True, help_text="格式如：#火箭#商业航天")
    icon_url = models.CharField(max_length=500, verbose_name="小图标URL", blank=True, null=True)
    cover_url = models.CharField(max_length=500, verbose_name="封面图片URL", blank=True, null=True)
    content = models.JSONField(default=get_encyclopedia_default_content, verbose_name="内容", blank=True, null=True)
    
    # 新增的图片相关字段
    scaletype = models.CharField(
        max_length=20, 
        choices=[
            ('centercrop', 'Center Crop'),
            ('centerinside', 'Center Inside')
        ],
        default='centercrop',
        verbose_name="图片缩放类型"
    )
    colorfield = models.CharField(
        max_length=7, 
        default='#FFFFFF',
        verbose_name="背景颜色",
        help_text="十六进制颜色代码，如：#FFFFFF"
    )
    
    class Meta:
        verbose_name = "百科"
        verbose_name_plural = "百科"
        ordering = ['name']
    
    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        if not self.content:
            self.content = get_encyclopedia_default_content()
        super().save(*args, **kwargs)

class EncyclopediaGroup(models.Model):
    """百科内容组 - 最外层结构"""
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=255, verbose_name="标题")
    description = models.TextField(blank=True, null=True, verbose_name="描述")
    
    
    class Meta:
        verbose_name = "百科-内容组"
        verbose_name_plural = "百科-内容组"
        # 移除基于时间的排序
        ordering = ['title']  # 改为按标题排序
    
    def __str__(self):
        return self.title

class EncyclopediaSection(models.Model):
    """百科内容组的子部分"""
    id = models.AutoField(primary_key=True)
    group = models.ForeignKey(EncyclopediaGroup, on_delete=models.CASCADE, related_name='sections', verbose_name="所属内容组")
    subtitle = models.CharField(max_length=255, verbose_name="子标题")
    order = models.PositiveIntegerField(default=0, verbose_name="排序", db_index=True)
    # 移除时间字段
    # created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    
    class Meta:
        verbose_name = "百科内容组子部分"
        verbose_name_plural = "百科内容组子部分"
        ordering = ['order']
        # 移除unique_together约束
        # unique_together = [['group', 'order']]
    
    def __str__(self):
        return f"{self.group.title} - {self.subtitle}"

class EncyclopediaSectionItem(models.Model):
    """百科内容组子部分中的百科词条关联"""
    id = models.AutoField(primary_key=True)
    section = models.ForeignKey(EncyclopediaSection, on_delete=models.CASCADE, related_name='items', verbose_name="所属子部分")
    encyclopedia = models.ForeignKey(Encyclopedia, on_delete=models.CASCADE, verbose_name="百科词条")
    order = models.PositiveIntegerField(default=0, verbose_name="排序")
    
    class Meta:
        verbose_name = "百科词条关联"
        verbose_name_plural = "百科词条关联"
        ordering = ['section', 'order']
        # 可以考虑移除或修改这个约束
        # unique_together = ['section', 'encyclopedia']  # 防止同一个子部分中重复添加相同的百科词条
    
    def __str__(self):
        return f"{self.section} - {self.encyclopedia.name}"

# 在LaunchSite模型后面添加以下代码

def get_institution_default_basic_info():
    return [
        {"title": "英文名", "content": ""},
        {"title": "别称/简称", "content": ""},
        {"title": "国家", "content": ""},
        {"title": "性质", "content": ""},
    ]

def get_institution_default_content():
    return [
        {"type": "h1", "content": "机构介绍"},
        {"type": "p", "content": "请在此填写机构介绍..."},
        {"type": "img", "url": "/images/institutions/default.jpg", "description": ""},
        {"type": "h1", "content": "机构图片"},
        {"type": "img", "url": "/images/institutions/area_default.jpg", "description": ""},
    ]

class Institution(models.Model):
    id = models.AutoField(primary_key=True)
    name = models.CharField(max_length=255, verbose_name="机构名称")
    logo = models.CharField(max_length=255, verbose_name="机构Logo URL")
    country = models.CharField(max_length=255, verbose_name="国家")
    nature = models.CharField(max_length=255, verbose_name="性质")
    image_url = models.CharField(max_length=255, verbose_name="图片URL")
    basic_info = models.JSONField(default=get_institution_default_basic_info, verbose_name="基本信息表格")
    content = models.JSONField(default=get_institution_default_content, verbose_name="正文内容")
    order = models.PositiveIntegerField(default=0, verbose_name="排序", db_index=True)
    
    # 新增相关机构字段
    related_institutions = models.ManyToManyField(
        'self',
        through='InstitutionRelation',
        symmetrical=False,
        related_name='related_by',
        verbose_name='相关机构'
    )
    
    class Meta:
        verbose_name = "机构"
        verbose_name_plural = "机构"
        ordering = ['order']
    
    def __str__(self):
        return self.name
    
    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)

# 新增机构关联模型
class InstitutionRelation(models.Model):
    from_institution = models.ForeignKey(
        Institution, 
        on_delete=models.CASCADE, 
        related_name='institution_relations',
        verbose_name="主机构"
    )
    to_institution = models.ForeignKey(
        Institution, 
        on_delete=models.CASCADE, 
        related_name='related_institution_relations',
        verbose_name="相关机构"
    )
    role = models.CharField(max_length=100, verbose_name="关系角色")  # 比如：子公司、合作伙伴、供应商等
    order = models.PositiveIntegerField(default=0, db_index=True, verbose_name="排序")

    class Meta:
        ordering = ['order']
        verbose_name = "机构关联关系"
        verbose_name_plural = "机构关联关系"
        unique_together = ['from_institution', 'to_institution']  # 防止重复关联

    def __str__(self):
        return f"{self.from_institution.name} - {self.to_institution.name} ({self.role})"
    
class MissionInstitutionMember(models.Model):
    mission_detail = models.ForeignKey(MissionDetail, on_delete=models.CASCADE)
    institution = models.ForeignKey('Institution', on_delete=models.CASCADE)
    role = models.CharField(max_length=100, verbose_name="机构角色")  # 比如：主承包商、发射服务商等
    order = models.PositiveIntegerField(default=0, db_index=True)  # 用于排序显示

    class Meta:
        ordering = ['order']
        verbose_name = "任务机构成员"
        verbose_name_plural = "任务机构成员"

    def __str__(self):
        return f"{self.institution.name} - {self.role}"


class KnowledgeQuestion(models.Model):
    """知识题库模型"""
    id = models.AutoField(primary_key=True, verbose_name="题目ID")
    question = models.TextField(verbose_name="题目名称")
    option_a = models.TextField(verbose_name="选项A")
    option_b = models.TextField(verbose_name="选项B")
    option_c = models.TextField(verbose_name="选项C")
    option_d = models.TextField(verbose_name="选项D")
    correct_answer = models.CharField(
        max_length=1, 
        choices=[
            ('A', 'A'),
            ('B', 'B'),
            ('C', 'C'),
            ('D', 'D')
        ],
        verbose_name="正确答案"
    )
    explanation = models.TextField(verbose_name="题目解析")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "知识题库"
        verbose_name_plural = "知识题库"
        ordering = ['-created_at']

    def __str__(self):
        return f"{self.id}. {self.question}"
